package com.example.weather

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.weather.ui.theme.WeatherTheme
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import kotlin.concurrent.thread

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        thread {
            val str:String? = readFileFromRaw(R.raw.citycode)
            val gson = Gson()
            val CityType = object : TypeToken<List<cityItem>>(){}.type
            var cities:List<cityItem> = gson.fromJson(str, CityType)
            cities = cities.filter { it.city_code!=""}
            runOnUiThread {
                val adapter =
                    ArrayAdapter<cityItem>(this, android.R.layout.simple_list_item_1, cities)
                val listView = findViewById<android.widget.ListView>(R.id.listView)
                listView.adapter = adapter
                listView.setOnItemClickListener { _, _, position, _ ->
                    Log.d("MainActivity", "position: $position")
                    val cityCode = cities[position].city_code
                    val intent = Intent(this,MainActivity2::class.java)
                    intent.putExtra("cityCode",cityCode)
                    startActivity(intent)
                }
            }
            Log.d("MainActivity", "$cities")
        }

    }

    fun readFileFromRaw(rawName: Int): String? {
        try {
            val inputReader = InputStreamReader(resources.openRawResource(rawName))
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            var result: String? = ""
            while (bufReader.readLine().also { line = it } != null) {
                result += line
            }
            return result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return ""
    }
}

